package com.ruoyi.framework.web.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.pay.domain.PayCoinUser;
import com.ruoyi.pay.service.IPayCoinUserService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wq.domain.WqNoticeChat;
import com.ruoyi.wq.domain.vo.WqNoticeChatVO;
import com.ruoyi.wq.service.IWqNoticeChatService;
import com.ruoyi.wx.domain.WxMaMsgForm;
import com.ruoyi.wx.service.WxMsgService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

@Component
public class NoticeChatService {
	
	@Autowired
	private IWqNoticeChatService wqNoticeChatService;
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
    private IPayCoinUserService payCoinUserService;
	
	@Autowired
    private WxMsgService wxMsgService;
	
	@Autowired
	private ISysConfigService sysConfigService;

	public WqNoticeChatVO add(WqNoticeChatVO wqNoticeChat) {
		return addUser(wqNoticeChat);
	}
	
	private WqNoticeChatVO addUser(WqNoticeChatVO wqNoticeChat){
		Long userId = SecurityUtils.getUserId();
		SysUser fromUser = sysUserService.getById(userId);
		
		if(userId.equals(wqNoticeChat.getToUserId())){
			throw new ServiceException("不能添加自己");
		}
		
		SysUser toUser = sysUserService.getById(wqNoticeChat.getToUserId());
		
		/*if(!"1".equals(toUser.getIsShow())){
			// 随机获取一个已经验证的用户
			toUser.setUserId(userId);
			List<SysUser> userList = sysUserService.getRandomUserListBySex(toUser);
			if(CollectionUtils.isEmpty(userList)){
				throw new ServiceException("微信为空");
			}
			toUser = userList.get(0);
		}*/
		if(StringUtils.isBlank(toUser.getWechat())){
			throw new ServiceException("微信为空");
		}
		
		QueryWrapper<WqNoticeChat> qw = new QueryWrapper<>();
		WqNoticeChat entity = new WqNoticeChat();
		entity.setFromUserId(userId);
		entity.setToUserId(wqNoticeChat.getToUserId());
		entity.setNoticeType("FROM");
		qw.setEntity(entity);
		WqNoticeChat fromChat = wqNoticeChatService.getOne(qw);
		
		QueryWrapper<WqNoticeChat> qw2 = new QueryWrapper<>();
		WqNoticeChat entity2 = new WqNoticeChat();
		entity2.setFromUserId(wqNoticeChat.getToUserId());
		entity2.setToUserId(userId);
		entity2.setNoticeType("TO");
		qw2.setEntity(entity2);
		WqNoticeChat toChat = wqNoticeChatService.getOne(qw2);
		if(fromChat == null && toChat == null){
			Integer coinNum = 880; // 新用户8.8元
			if("2".equals(wqNoticeChat.getPayType())){
				coinNum = sysConfigService.getConfig(fromUser.getAppId()).getAdRate();
			}
			
			if("0".equals(wqNoticeChat.getPayType())){
				coinNum = 0;
				if(toUser.getWechatCheck().equals("1")){
					coinNum = 880;
				}else{
					if(fromUser.getVipEndTime() == null || fromUser.getVipEndTime().compareTo(new Date()) < 0){
						throw new ServiceException("新用户体验会员已过期，请开通会员",788);
					}
				}
			}
			
			if(coinNum > payCoinUserService.getPayAmount()){
				throw new ServiceException("添加微信需要【"+coinNum+"】趣豆，请充值",888);
			}
			
			String noticeCode = RandomUtil.randomNumbers(5);
			fromChat = new WqNoticeChat();
			fromChat.setFromUserId(userId);
			fromChat.setToUserId(toUser.getUserId());
			fromChat.setNoticeCode(noticeCode);
			fromChat.setNoticeType("FROM");
			if("0".equals(fromUser.getSex())){
				fromChat.setRemark("他查看了您的微信，您获得了一个红包奖励，快通过他的微信申请，去索要验证码领奖吧，点击完善验证码领奖");
			}else{
				fromChat.setRemark("她查看了您的微信，您获得了一个红包奖励，快通过她的微信申请，去索要验证码领奖吧，点击完善验证码领奖");
			}
			wqNoticeChatService.saveOrUpdate(fromChat);
			
			
			if("1".equals(toUser.getIsShow())){
				WxMaMsgForm form = new WxMaMsgForm();
				form.setAppId(toUser.getAppId());
				form.setOpenId(toUser.getOpenId());
				Map<String,String> map = new HashMap<>();
				map.put("phrase1", "领奖通知");
				map.put("date2", DateUtil.now());
				map.put("name3", fromUser.getNickName());
				if("0".equals(fromUser.getSex())){
					map.put("thing4", "他查看了你的微信，点击完善验证码领奖");
				}else{
					map.put("thing4", "她查看了你的微信，点击完善验证码领奖");
				}
				form.setDataMap(map);
				form.setPage("pages/index?index=2");
				wxMsgService.sendSubscribeMsg(form);
			}
			
			toChat = new WqNoticeChat();
			toChat.setFromUserId(wqNoticeChat.getToUserId());
			toChat.setToUserId(userId);
			toChat.setOtherUserId(toUser.getUserId());
			toChat.setNoticeCode(noticeCode);
			toChat.setNoticeType("TO");
			if("0".equals(toUser.getSex())){
				toChat.setRemark("你查看了他的微信，请添加微信成功后，主动发送验证码给他，点击查看详情");
			}else{
				toChat.setRemark("你查看了她的微信，请添加微信成功后，主动发送验证码给她，点击查看详情");
			}
			wqNoticeChatService.saveOrUpdate(toChat);
			
			if(coinNum > 0){
				// 消耗金币
				PayCoinUser payCoinUser = new PayCoinUser();
				payCoinUser.setUserId(userId);
				payCoinUser.setCoinNum(coinNum);
				payCoinUser.setCoinType("1");
				payCoinUser.setSourceId(toChat.getId());
				payCoinUser.setIsPay("1"); // 充值
				payCoinUser.setRemark("查看微信");
	    		payCoinUserService.saveOrUpdate(payCoinUser);
	    		
	    		if(fromUser.getVisitUserId() != null){
	    			// 获得10%收益
	    			payCoinUser = new PayCoinUser();
		    		payCoinUser.setUserId(fromUser.getVisitUserId());
		    		payCoinUser.setCoinNum(coinNum/10);
		    		payCoinUser.setCoinType("0");
		    		payCoinUser.setIsPay("3"); // 佣金
		    		payCoinUser.setRemark("邀请人查看微信");
		    		payCoinUser.setStatus("0");
		    		payCoinUserService.saveOrUpdate(payCoinUser);
		    		
		    		BigDecimal money = BigDecimal.valueOf(coinNum/10).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
		    		WqNoticeChat noticeChat = new WqNoticeChat();
					noticeChat.setFromUserId(11637079L);
					noticeChat.setToUserId(fromUser.getVisitUserId());
					noticeChat.setNoticeType("SYSTEM");
					noticeChat.setRemark("恭喜您获得邀请人查看微信奖励"+money+"元！");
					wqNoticeChatService.saveOrUpdate(noticeChat);
	    		}
				
				// 发放奖励
	    		payCoinUser = new PayCoinUser();
	    		payCoinUser.setUserId(toUser.getUserId());
	    		payCoinUser.setCoinNum(coinNum/5);
	    		payCoinUser.setCoinType("0");
	    		payCoinUser.setSourceId(fromChat.getId());
	    		payCoinUser.setIsPay("3"); // 佣金
	    		payCoinUser.setRemark("微信被查看");
	    		payCoinUser.setStatus("1");
	    		payCoinUserService.saveOrUpdate(payCoinUser);
	    		
	    		if(toUser.getVisitUserId() != null){
	    			// 获得10%收益
	    			payCoinUser = new PayCoinUser();
		    		payCoinUser.setUserId(toUser.getVisitUserId());
		    		payCoinUser.setCoinNum(coinNum/10);
		    		payCoinUser.setCoinType("0");
		    		payCoinUser.setIsPay("3"); // 佣金
		    		payCoinUser.setRemark("邀请人被查看微信");
		    		payCoinUser.setStatus("0");
		    		payCoinUserService.saveOrUpdate(payCoinUser);
		    		
		    		
		    		BigDecimal money = BigDecimal.valueOf(coinNum/10).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
		    		WqNoticeChat noticeChat = new WqNoticeChat();
					noticeChat.setFromUserId(11637079L);
					noticeChat.setToUserId(toUser.getVisitUserId());
					noticeChat.setNoticeType("SYSTEM");
					noticeChat.setRemark("恭喜您获得邀请人被查看微信奖励"+money+"元！");
					wqNoticeChatService.saveOrUpdate(noticeChat);
	    		}
			}else{
				// 发放奖励
				PayCoinUser payCoinUser = new PayCoinUser();
	    		payCoinUser = new PayCoinUser();
	    		payCoinUser.setUserId(toUser.getUserId());
	    		payCoinUser.setCoinNum(30);
	    		payCoinUser.setCoinType("0");
	    		payCoinUser.setSourceId(fromChat.getId());
	    		payCoinUser.setIsPay("3"); // 佣金
	    		payCoinUser.setRemark("微信被查看");
	    		payCoinUser.setStatus("1");
	    		payCoinUserService.saveOrUpdate(payCoinUser);
	    		
	    		//fromUser.setPayNum(200);
	    		//sysUserService.updateById(fromUser);
			}
    		
    		// 用户查看次数增加
        	Integer readNum = toUser.getReadNum();
        	toUser.setReadNum(readNum+1);
        	sysUserService.updateById(toUser);
    		
    		WqNoticeChatVO chatVO = new WqNoticeChatVO();
    		chatVO.setWechat(toUser.getWechat());
    		chatVO.setNickName(fromUser.getNickName());
    		chatVO.setNoticeCode(fromChat.getNoticeCode());
    		return chatVO;
		}else{
			WqNoticeChatVO chatVO = new WqNoticeChatVO();
			if(fromChat != null){
				chatVO.setWechat(toUser.getWechat());
				chatVO.setNickName(fromUser.getNickName());
				chatVO.setNoticeCode(fromChat.getNoticeCode());
			}else{
				throw new ServiceException("请勿重复添加");
			}
			return chatVO;
		}
	}

	public WqNoticeChatVO getNoticeChatById(String id) {
		WqNoticeChat chat = wqNoticeChatService.getById(id);
		chat.setIsRead("1");
		wqNoticeChatService.updateById(chat);
		
		if("SYSTEM".equals(chat.getNoticeType()) || "USER".equals(chat.getNoticeType()) || "WECHAT".equals(chat.getNoticeType())){
			return null;
		}
		
		SysUser fromUser = sysUserService.getById(chat.getFromUserId());
		SysUser toUser = sysUserService.getById(chat.getToUserId());
		if(!"1".equals(fromUser.getIsShow())){
			fromUser = sysUserService.getById(chat.getOtherUserId());
		}
		
		WqNoticeChatVO chatVO = new WqNoticeChatVO();
		chatVO.setWechat(fromUser.getWechat());
		chatVO.setNickName(toUser.getNickName());
		chatVO.setNoticeCode(chat.getNoticeCode());
		return chatVO;
	}

	public AjaxResult checkCode(WqNoticeChat wqNoticeChat) {
		PayCoinUser coinUser = payCoinUserService.getCoinUserBySrouceId(wqNoticeChat.getId());
		if(coinUser == null){
			throw new ServiceException("未找到订单");
		}
		WqNoticeChat chat = wqNoticeChatService.getById(wqNoticeChat.getId());
		if("1".equals(chat.getIsRead())){
			throw new ServiceException("请不要重复领取");
		}
		if(chat.getNoticeCode().equals(wqNoticeChat.getNoticeCode())){
			chat.setIsRead("1");
			wqNoticeChatService.updateById(chat);
			
			// 微信认证
			SysUser toUser = sysUserService.getById(chat.getToUserId());
			toUser.setWechatCheck("1");
			sysUserService.updateById(toUser);
			
			// 领取奖励
			coinUser.setStatus("0");
			payCoinUserService.updateById(coinUser);
		}else{
			throw new ServiceException("验证码错误");
		}
		return AjaxResult.success();
	}

	public AjaxResult checkUser(WqNoticeChat wqNoticeChat) {
		SysUser user = sysUserService.getById(wqNoticeChat.getToUserId());
		SysUser fromUser = sysUserService.getById(SecurityUtils.getUserId());
		if(!"1".equals(user.getIsShow())){
			return AjaxResult.success();
		}
		if("1".equals(user.getWechatCheck())){
			QueryWrapper<WqNoticeChat> qw = new QueryWrapper<>();
			WqNoticeChat entity = new WqNoticeChat();
			entity.setNoticeType("USER");
			entity.setFromUserId(SecurityUtils.getUserId());
			entity.setToUserId(wqNoticeChat.getToUserId());
			qw.setEntity(entity);
			WqNoticeChat noticeChat = wqNoticeChatService.getOne(qw);
			if(noticeChat == null){
				noticeChat = new WqNoticeChat();
				noticeChat.setFromUserId(SecurityUtils.getUserId());
				noticeChat.setToUserId(wqNoticeChat.getToUserId());
				
				noticeChat.setNoticeType("USER");
				noticeChat.setRemark("我想认识你，邀请你完成真人认证，请在个人中心申请真人认证");
				wqNoticeChatService.saveOrUpdate(noticeChat);
			}
		}else{
			QueryWrapper<WqNoticeChat> qw = new QueryWrapper<>();
			WqNoticeChat entity = new WqNoticeChat();
			entity.setNoticeType("WECHAT");
			entity.setFromUserId(SecurityUtils.getUserId());
			entity.setToUserId(wqNoticeChat.getToUserId());
			qw.setEntity(entity);
			WqNoticeChat noticeChat = wqNoticeChatService.getOne(qw);
			if(noticeChat == null){
				noticeChat = new WqNoticeChat();
				noticeChat.setFromUserId(SecurityUtils.getUserId());
				noticeChat.setToUserId(wqNoticeChat.getToUserId());
				
				noticeChat.setNoticeType("WECHAT");
				noticeChat.setRemark("我想认识你，邀请你关闭勿扰模式，请在个人资料打开微信查看权限");
				wqNoticeChatService.saveOrUpdate(noticeChat);
				
				user.setIsShow("0");
				sysUserService.updateById(user);
				
				if(fromUser.getAppId().equals(user.getAppId())){
					WxMaMsgForm form = new WxMaMsgForm();
					form.setAppId(user.getAppId());
					form.setOpenId(user.getOpenId());
					Map<String,String> map = new HashMap<>();
					map.put("phrase1", "邀请通知");
					map.put("date2", DateUtil.now());
					map.put("name3", fromUser.getNickName());
					if("0".equals(fromUser.getSex())){
						map.put("thing4", "他想认识你，点击查看详情");
					}else{
						map.put("thing4", "她想认识你，点击查看详情");
					}
					form.setDataMap(map);
					form.setPage("pages/index?index=1");
					wxMsgService.sendSubscribeMsg(form);
				}
			}
		}
		
		return AjaxResult.success();
	}

	public int getNoticeCount() {
		QueryWrapper<WqNoticeChat> qw = new QueryWrapper<>();
		WqNoticeChat entity = new WqNoticeChat();
		entity.setToUserId(SecurityUtils.getUserId());
		entity.setIsRead("0");
		qw.setEntity(entity);
		return wqNoticeChatService.count(qw);
	}

}
